<template>
  <div class="ai-chat-page">
    <h2>AI智能客服</h2>
    <div class="chat-history">
      <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.type]">
        {{ message.content }}
      </div>
    </div>
<div>
         <el-input
        v-model="userInput"
        placeholder="请输入您的问题"
        @keyup.enter="sendMessage"
      ></el-input>
      <el-button @click="sendMessage">发送</el-button> 
</div>


  </div>
</template>

<script>
// 按需引入所需的 ElementPlus 组件
import { ElInput, ElButton } from 'element-plus';
import 'element-plus/dist/index.css';

export default {
  // 注册组件
  components: {
    ElInput,
    ElButton
  },
  data() {
    return {
      userInput: '',
      chatMessages: [],
      eventSource: null
    };
  },
  methods: {
    sendMessage() {
      if (this.userInput.trim() === '') return;

      // 添加用户消息到聊天历史
      this.chatMessages.push({
        type: 'user',
        content: this.userInput
      });

      // 初始化 SSE 连接
      this.eventSource = new EventSource(`http://localhost:8090/sse/ai/stream?prompt=${encodeURIComponent(this.userInput)}`);

      let aiResponse = '';
      this.eventSource.onmessage = (event) => {
        console.log('收到 SSE 消息:', event.data); // 添加日志
        const token = event.data.replace('data: ', '');
        aiResponse += token;
        // 更新 AI 回复消息
        const lastMessage = this.chatMessages[this.chatMessages.length - 1];
        if (lastMessage && lastMessage.type === 'ai') {
          lastMessage.content = aiResponse;
        } else {
          this.chatMessages.push({
            type: 'ai',
            content: aiResponse
          });
        }
      };

      this.eventSource.onerror = (error) => {
        console.log('SSE 连接可能出现问题，检查状态码:', this.eventSource.readyState);
        if (this.eventSource.readyState === EventSource.CLOSED) {
          console.error('SSE 连接已关闭:', error);
        } else {
          console.warn('SSE 连接暂时不稳定，但可能会恢复:', error);
        }
        this.eventSource.close();
      };

      this.userInput = '';
    }
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  }
};
</script>

<style scoped>
.ai-chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  border-bottom: 1px solid #dcdfe6;
}

.message {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
}

.user {
  background-color: #e6f7ff;
  text-align: right;
}

.ai {
  background-color: #f0f2f5;
}

.input-container {
  display: flex;
  padding: 16px;
  gap: 10px;
}

.el-input {
  flex: 1;
}
</style>